<template>
  <a-row id="globalHeader" align="center" :wrap="false">
    <a-col flex="auto">
      <a-menu
        theme="dark"
        mode="horizontal"
        v-model:selectedKeys="selectedKeys"
        @select="doMenuClick"
        :style="{ lineHeight: '64px' }"
      >
        <a-menu-item
          key="0"
          :style="{ padding: 0, marginRight: '38px' }"
          disabled
        >
          <div class="title-bar">
            <img class="logo" src="../../public/logo.png" alt="" />
            <div class="title">智能BI</div>
          </div>
        </a-menu-item>
        <a-menu-item v-for="item in visibleRoutes" :key="item.path">
          {{ item.name }}
        </a-menu-item>
      </a-menu>
    </a-col>
    <a-col flex="100px">
      <a style="color: #fff" v-if="store.state.user.token">
        {{ store.state.user?.loginUser.userName }}
      </a>
      <a
        style="color: #fff; margin-left: 22px"
        v-if="store.state.user?.token"
        @click="logout"
      >
        退出登录
      </a>
      <a style="color: #fff" v-if="!store.state.user.token" @click="login">
        登录
      </a>
    </a-col>
  </a-row>
</template>

<script setup lang="ts">
import { routes } from "@/router/routes";
import { useRouter } from "vue-router";
import { computed, onMounted, ref } from "vue";
import { useStore } from "vuex";
import checkAccess from "@/access/checkAccess";
import { UserControllerService } from "../../generated";
import { getToken, removeToken } from "@/utils/auth";

const selectedKeys = ref(["/"]);
const router = useRouter();
const store = useStore();
// 展示在菜单的路由数组
const visibleRoutes = computed(() => {
  return routes.filter((item, index) => {
    if (item.meta?.hideInMenu) {
      return false;
    }
    // 根据权限过滤菜单
    return checkAccess(
      store.state.user.loginUser,
      item?.meta?.access as string
    );
  });
});
// 路由跳转后，更新选中的菜单项
router.afterEach((to, from, failure) => {
  selectedKeys.value = [to.path];
});

// 默认主页
const doMenuClick = ({ item, key, keyPath }: any) => {
  router.push({ path: key });
};

const logout = async () => {
  const res = await UserControllerService.logoutUsingPost();
  if (res.code === 200) {
    await store.dispatch("user/getLoginUser");
    router.push({ path: "/" });
  }
};
const login = async () => {
  router.push("/user/login");
};

onMounted(async () => {
  let res = await UserControllerService.getLoginUserUsingGet();
  if (!res.data) {
    removeToken();
  }
});
</script>

<style scoped>
.title-bar {
  display: flex;
  align-items: center;
}

.title {
  color: #c9c6c6;
  margin-left: 16px;
}

.logo {
  height: 48px;
}
</style>
